package top.mihile.cableMonitorMedia.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import top.mihile.cableMonitorMedia.CableMonitorMediaServer;
import top.mihile.cableMonitorMedia.utils.FfmpegVersionAdapter;
import top.mihile.cableMonitorMedia.utils.RtspTransThread;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Mihile azuretodd@foxmail.com
 * @date 0272020/5/27
 */
@Service
public class RtspTransService {
    @Value("${server.port}")
    private Integer port;

    public static Map<UUID,Thread> ffmpegProcessMap = new ConcurrentHashMap<>();
    public static Map<UUID,Timer> ffmpegProcessTimerMap = new ConcurrentHashMap<>();

    /**
     * 服务启动时检测 FFmpeg 版本
     */
    @PostConstruct
    public void init() {
        System.out.println("========== FFmpeg 版本检测 ==========");
        FfmpegVersionAdapter.detectVersion();
        System.out.println("FFmpeg 版本: " + FfmpegVersionAdapter.getFullVersion());
        System.out.println("主版本号: " + FfmpegVersionAdapter.getMajorVersion());
        System.out.println("是否为 7.0+: " + FfmpegVersionAdapter.isVersion7OrHigher());
        System.out.println("RTSP 协议优化: " + (FfmpegVersionAdapter.isVersion7OrHigher() ? "已启用" : "标准模式"));
        System.out.println("====================================");
    }

    /**
     * 启动 RTSP 转码（自动适配 FFmpeg 版本）
     */
    public void doStartTrans(String url, UUID playChannel){
        // 使用版本适配器构建兼容的命令
        List<String> commands = FfmpegVersionAdapter.buildCompatibleCommand(
            url, 
            port, 
            playChannel.toString(), 
            CableMonitorMediaServer.audio
        );
        
        // 打印命令用于调试
        FfmpegVersionAdapter.printCommand(commands);

        RtspTransThread rtspTransThread = new RtspTransThread(commands);
        rtspTransThread.start();

        registProcess(playChannel,rtspTransThread);
    }
    
    /**
     * 启动 RTSP 转码（自定义分辨率）
     * 
     * @param url RTSP URL
     * @param playChannel 播放通道
     * @param resolution 分辨率，如 "1920x1080", "1280x720", "640x480" 等
     */
    public void doStartTransWithResolution(String url, UUID playChannel, String resolution){
        // 使用自适应命令构建器
        List<String> commands = FfmpegVersionAdapter.buildAdaptiveCommand(
            url, 
            port, 
            playChannel.toString(), 
            CableMonitorMediaServer.audio,
            resolution
        );
        
        // 打印命令用于调试
        FfmpegVersionAdapter.printCommand(commands);

        RtspTransThread rtspTransThread = new RtspTransThread(commands);
        rtspTransThread.start();

        registProcess(playChannel,rtspTransThread);
    }

    public  void registProcess(UUID playChannel,Thread thread){
        ffmpegProcessMap.put(playChannel,thread);
    }
}
